package com.chilly.other.thread;

import java.util.concurrent.Semaphore;

/**
 * semaphore 信号量：控制同时访问的线程个数
 * Created by Chilly Cui on 2020/12/5.
 */
public class SemaphoreDemo {

    public static void main(String[] args) {
        int workerNum = 8; //工人数量
        int machineNum = 4;//机器数量

        Semaphore semaphore = new Semaphore(machineNum);
        for (int i = 0; i < workerNum; i++) {
            new Worker(i, semaphore).start();
        }
    }

    static class Worker extends Thread {
        private int workerNum;
        private Semaphore semaphore;

        public Worker(int workerNum, Semaphore semaphore) {
            this.workerNum = workerNum;
            this.semaphore = semaphore;
        }

        @Override
        public void run() {
            try {
                semaphore.acquire();
                System.out.println("工人：" + workerNum + "占用机器在生产。。。");
                Thread.sleep(2000);
                System.out.println("工人：" + workerNum + "释放机器");
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
